﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Windows.Forms;
using MyLog;

namespace Notification
{
    public partial class FrmAutoUpdater : Form
    {
        private int index = 0;
        private WebClient webClient;

        public FrmAutoUpdater()
        {
            InitializeComponent();
        }

        private void FrmAutoUpdater_Load(object sender, EventArgs e)
        {
            webClient = new WebClient();
            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
            webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;

            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"Update\")) {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + @"Update\");
            }
            txtUpdateDescription.Text = Program.UpdateInfo.UpdateDescription;
            DownloadNext();
        }

        /// <summary>
        ///     下载完成时触发的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                LogHelper.WriteLog("下载错误",e.Error);
                MessageBox.Show(@"下载错误：" + e.Error.Message, @"下载提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (e.Cancelled)
            {
                MessageBox.Show(@"下载被取消。", @"下载提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                index++;
                DownloadNext();
            }
        }

        /// <summary>
        ///     下载过程中触发的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            lblTotalProgress.Text = string.Format("总进度：({0}/{1})", index, Program.UpdateInfo.DownloadFiles.Count);
            pbarTotal.Value = index / Program.UpdateInfo.DownloadFiles.Count;

            lblCurrentProgress.Text = string.Format("当前进度：文件[{0}]，进度{1}/{2}", Program.UpdateInfo.DownloadFiles[index],
                FileHelper.TranslateFileSize(e.BytesReceived), FileHelper.TranslateFileSize(e.TotalBytesToReceive));
            pbarCurrent.Value = e.ProgressPercentage;
        }

        public void DownloadNext()
        {
            if (index < Program.UpdateInfo.DownloadFiles.Count)
            {
                var remoteFile = Program.UpdateInfo.ReleaseUrl + @"/" + Program.UpdateInfo.DownloadFiles[index];
                var localFile = AppDomain.CurrentDomain.BaseDirectory + @"Update\" + Program.UpdateInfo.DownloadFiles[index];
                LogHelper.WriteLog("准备下载文件：" + localFile);
                webClient.DownloadFileAsync(new Uri(remoteFile), localFile);
            }
            else
            {
                pbarCurrent.Value = pbarCurrent.Maximum;
                pbarTotal.Value = pbarTotal.Maximum;
                MessageBox.Show(@"全部下载完成。", @"下载提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                RestartApp();
            }
        }

        private void RestartApp()
        {
            var appName = AppDomain.CurrentDomain.BaseDirectory + @"Update\Notification.exe";
            var param = "zw-url://" +  Program.CurrentUserId + "," + Program.CurrentUserName;
            Process.Start(appName, param);

            Close();
            Application.Exit();
        }
    }
}